package listbyorder.access101_200.test132;

import java.util.HashMap;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/10 13:21
 */
public class Solution2 {

    // 方法二： 使用map进行优化
    public int minCut(String s) {
        boolean dp[][] = new boolean[s.length()][s.length()];
        for (int len = 1; len <= s.length(); len++) {
            for (int i = 0; i + len <= s.length(); i++) {
                int j = i + len - 1;
                if (len == 1) {
                    dp[i][j] = true;
                } else {
                    dp[i][j] = s.charAt(i) == s.charAt(j) && (len <= 3 || dp[i + 1][j - 1]);
                }
            }
        }
        HashMap<Integer, Integer> memo = new HashMap<>();
        return minCutHelper(s, 0, dp, memo);
    }

    private int minCutHelper(String s, int start, boolean[][] dp, HashMap<Integer, Integer> memo) {
        if (dp[start][s.length() - 1]) {
            return 0;
        }
        if (memo.containsKey(start)) return memo.get(start);
        int min = Integer.MAX_VALUE;
        for (int i = start; i < s.length(); i++) {
            if (dp[start][i]) {
                min = Math.min(min, 1 + minCutHelper(s, i + 1, dp, memo));
            }
        }
        memo.put(start, min);
        return min;
    }
}
